from flask import request
from flask_restful import Resource, reqparse
from flask_shop import models, db
from flask_shop.role import role_api, role_bp


class Roles(Resource):
    def get(self):
        """
        获取角色列表
        :return:
        """
        try:
            roles = models.Role.query.all()
            role_list = []
            for role in roles:
                role_list.append(role.to_dict())
            return {'status': 200, 'msg': '获取角色列表成功', 'data': role_list}
        except Exception as e:
            return {'status': 400, 'msg': '获取列表失败'}

    def post(self):
        """
        增加角色
        :return:
        """
        name = request.get_json().get('name')
        desc = request.get_json().get('desc')
        try:
            role = models.Role.query.filter(models.Role.name == name).first()
            if role:
                return {'status': 400, 'msg': '角色已存在'}
        except Exception as e:
            print(e)

        role = models.Role(name=name, desc=desc)
        db.session.add(role)
        db.session.commit()
        return {'status': 200, 'msg': '添加成功'}


role_api.add_resource(Roles, '/')


class Role(Resource):
    def put(self, id):
        role = models.Role.query.get(id)
        parser = reqparse.RequestParser()
        # 添加参数
        parser.add_argument('name', type=str, required=True, help='请输入角色名称')
        parser.add_argument('desc', type=str)
        args = parser.parse_args()
        if args.get('name'):
            role.name = args.get('name')
        if args.get('desc'):
            role.desc = args.get('desc')
        db.session.commit()
        return {'status': 200, 'msg': '修改成功', 'data': role.to_dict()}

    def delete(self, id):
        try:
            role = models.Role.query.get(id)
            if role:
                db.session.delete(role)
                db.session.commit()
            return {'status': 200, 'msg': '删除成功'}
        except Exception as e:
            print(e)
            return {'status': 400, 'msg': '删除失败'}


role_api.add_resource(Role, '/<int:id>')


@role_bp.route('/<int:rid>/<int:mid>/')
def del_menu(rid: int, mid: int):
    # 查找当前的角色信息
    role = models.Role.query.get(rid)
    # 查找当前的菜单信息
    menu = models.Menu.query.get(mid)
    # 判断当前角色与菜单是否存在
    if all([role, menu]):
        # 判断当前角色是否有该权限
        if menu in role.menus:
            # 删除当前角色的权限
            role.menus.remove(menu)
            # 判断当前菜单是否是父级菜单
            if menu.level == 1:
                # 删除该权限所有的二级权限
                for t in menu.children:
                    if t in role.menus:
                        role.menus.remove(t)
        db.session.commit()
        return {'status': 200, 'msg': '删除权限成功'}
    else:
        return {'status': 500, 'msg': '角色或菜单不存在'}


@role_bp.route('/<int:rid>/', methods=['POST'])
def set_menu(rid: int):
    # 获取当前角色信息
    try:
        role = models.Role.query.get(rid)
        # 获取要分配的权限
        mids = request.get_json().get('mids')
        role.menus = []
        # 分配权限
        mids = mids.split(',')
        for m in mids:
            if m == '':
                continue
            # 获取权限
            menu = models.Menu.query.get(int(m))
            role.menus.append(menu)
        # 保存数据库
        db.session.commit()
        # 返回结果
        return {'status': 200, 'msg': '权限设置成功'}
    except Exception as e:
        return {'status': 500, 'msg': '分配角色失败'}
